import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { costRecordApi } from '@/apis/costRecord';

/**
 * 成本记录管理相关的hooks
 */
export const useCostRecord = () => {
  // 状态管理
  const loading = ref(false);
  const dialogVisible = ref(false);
  const dialogTitle = ref('');
  const formRef = ref(null);

  // 搜索表单
  const searchForm = reactive({
    keyword: '',
    departmentId: '',
    costItemId: '',
    applicantId: '',
    dateRange: []
  });

  // 分页信息
  const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
    loading: false
  });

  // 表单数据
  const formData = reactive({
    id: '',
    departmentId: '',
    costItemId: '',
    applicantId: '',
    amount: '',
    occurrenceDate: '',
    recordDate: '',
    costType: '1',
    paymentStatus: '1',
    description: ''
  });

  // 表单验证规则
  const formRules = reactive({
    departmentId: [
      { required: true, message: '请选择部门', trigger: 'change' }
    ],
    costItemId: [
      { required: true, message: '请选择成本项目', trigger: 'change' }
    ],
    amount: [
      { required: true, message: '请输入成本金额', trigger: 'blur' },
      { type: 'number', min: 0.01, message: '成本金额必须大于0', trigger: 'blur' }
    ],
    occurrenceDate: [
      { required: true, message: '请选择发生日期', trigger: 'change' }
    ],
    recordDate: [
      { required: true, message: '请选择记录日期', trigger: 'change' }
    ],
    description: [
      { max: 500, message: '成本描述不能超过500个字符', trigger: 'blur' }
    ]
  });

  // 审批相关状态
  const approveDialogVisible = ref(false);
  const approveFormRef = ref(null);
  
  // 审批表单数据
  const approveForm = reactive({
    id: '',
    recordNo: '',
    departmentName: '',
    applicantName: '',
    amount: '',
    description: '',
    approvalStatus: '',
    approvalComment: ''
  });
  
  // 审批表单验证规则
  const approveFormRules = reactive({
    approvalStatus: [
      { required: true, message: '请选择审批状态', trigger: 'change' }
    ],
    approvalComment: [
      { required: true, message: '请输入审批意见', trigger: 'blur' },
      { max: 500, message: '审批意见不能超过500个字符', trigger: 'blur' }
    ]
  });

  // 部门选项
  const departmentOptions = ref([]);

  // 成本项目选项
  const costItemOptions = ref([]);

  // 用户选项
  const userOptions = ref([]);

  // 获取部门列表
  const getDepartments = async () => {
    try {
      const response = await costRecordApi.getDepartments();
      if (response && response.data) {
        departmentOptions.value = (response.data || []).map(dept => ({
          id: dept.id,
          deptName: dept.deptName || dept.dept_name || dept.name
        }));
      }
    } catch (error) {
      console.error('获取部门列表失败:', error);
      ElMessage.error('获取部门列表失败');
      // 失败时使用默认数据
      departmentOptions.value = [
        { id: 1, deptName: '研发部' },
        { id: 2, deptName: '市场部' },
        { id: 3, deptName: '财务部' }
      ];
    }
  };

  // 获取成本项目列表
  const getCostItems = async () => {
    try {
      const response = await costRecordApi.getCostItems();
      if (response && response.data) {
        costItemOptions.value = (response.data || []).map(item => ({
          id: item.id,
          itemName: item.itemName || item.item_name || item.name
        }));
      }
    } catch (error) {
      console.error('获取成本项目列表失败:', error);
      ElMessage.error('获取成本项目列表失败');
      // 失败时使用默认数据
      costItemOptions.value = [
        { id: 1, itemName: '人力成本' },
        { id: 2, itemName: '物料成本' },
        { id: 3, itemName: '设备成本' }
      ];
    }
  };

  // 获取用户列表
  const getUsers = async () => {
    try {
      const response = await costRecordApi.getUsers();
      if (response && response.data) {
        userOptions.value = (response.data || []).map(user => ({
          id: user.id,
          realName: user.realName || user.real_name || user.name
        }));
      }
    } catch (error) {
      console.error('获取用户列表失败:', error);
      ElMessage.error('获取用户列表失败');
      // 失败时使用默认数据
      userOptions.value = [
        { id: 1, realName: '张三' },
        { id: 2, realName: '李四' },
        { id: 3, realName: '王五' }
      ];
    }
  };

  // 初始化基础数据
  const initializeData = async () => {
    try {
      await Promise.all([
        getDepartments(),
        getCostItems(),
        getUsers()
      ]);
    } catch (error) {
      console.error('初始化数据失败:', error);
    }
  };

  // 模拟成本记录数据
  const costRecordsList = ref([]);

  // 模拟数据生成
  const generateMockData = () => {
    const mockData = [];
    const recordNos = ['CR202500001', 'CR202500002', 'CR202500003', 'CR202500004', 'CR202500005'];
    const departments = [{ id: 8, name: '运营部' }, { id: 1, name: '研发部' }, { id: 3, name: '财务部' }, { id: 6, name: '销售部' }];
    const costItems = [{ id: 6, name: '营销费用' }, { id: 10, name: '员工福利' }, { id: 4, name: '行政费用' }, { id: 5, name: '差旅费用' }, { id: 8, name: '系统维护费用' }];
    const applicants = [{ id: 7, name: '周九' }, { id: 3, name: '王五' }, { id: 1, name: '张三' }, { id: 6, name: '孙八' }, { id: 5, name: '钱七' }];
    const descriptions = ['项目执行费用', '员工培训费用', '部门活动经费', '设备采购费用', '系统维护费用'];

    for (let i = 0; i < 20; i++) {
      const idx = i % 5;
      mockData.push({
        id: i + 1,
        recordNo: recordNos[idx] + (i > 4 ? i : ''),
        departmentId: departments[idx % departments.length].id,
        departmentName: departments[idx % departments.length].name,
        costItemId: costItems[idx % costItems.length].id,
        costItemName: costItems[idx % costItems.length].name,
        applicantId: applicants[idx % applicants.length].id,
        applicantName: applicants[idx % applicants.length].name,
        amount: (Math.random() * 50000 + 1000).toFixed(2),
        occurrenceDate: `2025-${String(Math.floor(Math.random() * 12) + 1).padStart(2, '0')}-${String(Math.floor(Math.random() * 28) + 1).padStart(2, '0')}`,
        recordDate: `2025-${String(Math.floor(Math.random() * 12) + 1).padStart(2, '0')}-${String(Math.floor(Math.random() * 28) + 1).padStart(2, '0')}`,
        costType: Math.floor(Math.random() * 3) + 1,
        paymentStatus: Math.floor(Math.random() * 3) + 1,
        approvalStatus: Math.floor(Math.random() * 3) + 1,
        description: descriptions[idx]
      });
    }

    return mockData;
  };

  // 获取成本记录列表
  const getCostRecords = async () => {
    // 确保基础数据已加载
    if (departmentOptions.value.length === 0 || costItemOptions.value.length === 0 || userOptions.value.length === 0) {
      await initializeData();
    }
    
    // 使用pagination的loading状态替代单独的loading
    pagination.loading = true;
    try {
      // 构建API请求参数
      const apiParams = {
        page: pagination.currentPage,
        pageSize: pagination.pageSize,
        keyword: searchForm.keyword,
        departmentId: searchForm.departmentId,
        costItemId: searchForm.costItemId,
        applicantId: searchForm.applicantId,
        // 日期格式转换：去除时区信息，转换为yyyy-MM-dd格式
        startDate: searchForm.dateRange && searchForm.dateRange[0] ? new Date(searchForm.dateRange[0]).toISOString().split('T')[0] : null,
        endDate: searchForm.dateRange && searchForm.dateRange[1] ? new Date(searchForm.dateRange[1]).toISOString().split('T')[0] : null
      };

      // 调用真实API
      const response = await costRecordApi.getCostRecords(apiParams);

      // 增加空值检查
      if (!response || !response.data) {
        throw new Error('API返回数据为空');
      }

      // 数据字段映射转换
      const transformedRecords = (response.data.records || []).map(record => ({
        id: record.id,
        recordNo: record.recordNo || record.record_no,
        departmentId: record.departmentId || record.department_id,
        departmentName: record.departmentName || record.department_name,
        costItemId: record.costItemId || record.cost_item_id,
        costItemName: record.costItemName || record.cost_item_name,
        applicantId: record.applicantId || record.applicant_id,
        applicantName: record.applicantName || record.applicant_name,
        amount: record.amount,
        occurrenceDate: record.occurrenceDate || record.occurrence_date,
        recordDate: record.recordDate || record.record_date,
        costType: record.costType || record.cost_type,
        paymentStatus: record.paymentStatus || record.payment_status,
        approvalStatus: record.approvalStatus || record.approval_status,
        description: record.description
      }));

      // 更新数据
      costRecordsList.value = transformedRecords;
      pagination.total = response.data.total || 0;

      // 显示无数据信息
      if (transformedRecords.length === 0) {
        ElMessage.info('暂无符合条件的数据');
      }
    } catch (error) {
      console.error('获取成本记录失败:', error);
      // 显示错误提示
      ElMessage.error('获取成本记录失败，请稍后重试');
    } finally {
      pagination.loading = false;
    }
  };

  // 格式化货币
  const formatCurrency = (value) => {
    return new Intl.NumberFormat('zh-CN', {
      style: 'currency',
      currency: 'CNY'
    }).format(value);
  };

  // 获取成本性质标签
  const getCostTypeTag = (type) => {
    const tags = {
      1: { label: '实际成本', type: 'success' },
      2: { label: '预算成本', type: 'warning' },
      3: { label: '预估成本', type: 'info' }
    };
    return tags[type] || { label: '未知', type: 'default' };
  };

  // 获取支付状态标签
  const getPaymentStatusTag = (status) => {
    const tags = {
      1: { label: '未支付', type: 'danger' },
      2: { label: '已支付', type: 'success' },
      3: { label: '已报销', type: 'primary' }
    };
    return tags[status] || { label: '未知', type: 'default' };
  };

  // 获取审批状态标签
  const getApprovalStatusTag = (status) => {
    const tags = {
      1: { label: '待审批', type: 'warning' },
      2: { label: '已通过', type: 'success' },
      3: { label: '已驳回', type: 'danger' }
    };
    return tags[status] || { label: '未知', type: 'default' };
  };

  // 搜索
  const handleSearch = async () => {
    pagination.loading = true;
    pagination.currentPage = 1;
    try {
      // 构建API请求参数
      const apiParams = {
        keyword: searchForm.keyword,
        departmentId: searchForm.departmentId,
        costItemId: searchForm.costItemId,
        applicantId: searchForm.applicantId,
        // 日期格式转换：去除时区信息，转换为yyyy-MM-dd格式
        startDate: searchForm.dateRange && searchForm.dateRange[0] ? new Date(searchForm.dateRange[0]).toISOString().split('T')[0] : null,
        endDate: searchForm.dateRange && searchForm.dateRange[1] ? new Date(searchForm.dateRange[1]).toISOString().split('T')[0] : null,
        page: pagination.currentPage,
        pageSize: pagination.pageSize
      };

      // 调用搜索API
      const response = await costRecordApi.searchCostRecords(apiParams);

      // 增加空值检查
      if (!response || !response.data) {
        throw new Error('API返回数据为空');
      }

      // 数据字段映射转换
      const transformedRecords = (response.data.records || []).map(record => ({
        id: record.id,
        recordNo: record.recordNo || record.record_no,
        departmentId: record.departmentId || record.department_id,
        departmentName: record.departmentName || record.department_name,
        costItemId: record.costItemId || record.cost_item_id,
        costItemName: record.costItemName || record.cost_item_name,
        applicantId: record.applicantId || record.applicant_id,
        applicantName: record.applicantName || record.applicant_name,
        amount: record.amount,
        occurrenceDate: record.occurrenceDate || record.occurrence_date,
        recordDate: record.recordDate || record.record_date,
        costType: record.costType || record.cost_type,
        paymentStatus: record.paymentStatus || record.payment_status,
        approvalStatus: record.approvalStatus || record.approval_status,
        description: record.description
      }));

      // 更新数据
      costRecordsList.value = transformedRecords;
      pagination.total = response.data.total || 0;

      // 显示搜索结果提示
      ElMessage.success('搜索成功');
    } catch (error) {
      console.error('搜索成本记录失败:', error);
      // 显示错误提示
      ElMessage.error('搜索失败，请稍后重试');
      // 失败时尝试使用原有的getCostRecords作为备选
      try {
        await getCostRecords();
      } catch (fallbackError) {
        console.error('备选获取方式也失败:', fallbackError);
      }
    } finally {
      pagination.loading = false;
    }
  };

  // 重置
  const handleReset = () => {
    Object.keys(searchForm).forEach(key => {
      if (Array.isArray(searchForm[key])) {
        searchForm[key] = [];
      } else {
        searchForm[key] = '';
      }
    });
    pagination.currentPage = 1;
    getCostRecords();
    ElMessage.success('筛选条件已重置');
  };

  // 快速筛选
  const quickFilter = (type, value) => {
    switch (type) {
      case 'department':
        searchForm.departmentId = value;
        break;
      case 'costItem':
        searchForm.costItemId = value;
        break;
      case 'status':
        // 这里可以添加状态快速筛选
        break;
    }
    pagination.currentPage = 1;
    getCostRecords();
  };

  // 新增
  const handleAdd = () => {
    dialogTitle.value = '新增成本记录';
    // 重置表单
    if (formRef.value) {
      formRef.value.resetFields();
    }
    resetFormData();
    dialogVisible.value = true;
  };

  // 查看
  const handleView = async (row) => {
    dialogTitle.value = '查看成本记录';
    try {
      // 调用API获取详细信息
      const response = await costRecordApi.getCostRecordById(row.id);

      // 数据字段映射转换
      const record = response.data;
      const formRecord = {
        id: record.id,
        departmentId: record.departmentId || record.department_id,
        costItemId: record.costItemId || record.cost_item_id,
        applicantId: record.applicantId || record.applicant_id,
        amount: record.amount,
        occurrenceDate: record.occurrenceDate || record.occurrence_date,
        recordDate: record.recordDate || record.record_date,
        // 确保costType和paymentStatus是字符串类型，以匹配select选项
        costType: String(record.costType || record.cost_type),
        paymentStatus: String(record.paymentStatus || record.payment_status),
        approvalStatus: record.approvalStatus || record.approval_status,
        description: record.description,
        recordNo: record.recordNo || record.record_no
      };

      // 复制数据到表单
      Object.assign(formData, formRecord);
      dialogVisible.value = true;
    } catch (error) {
      console.error('获取成本记录详情失败:', error);
      ElMessage.error('获取详情失败，请稍后重试');
    }
  };

  // 编辑
  const handleEdit = async (row) => {
    dialogTitle.value = '编辑成本记录';
    try {
      // 调用API获取详细信息
      const response = await costRecordApi.getCostRecordById(row.id);

      // 数据字段映射转换
      const record = response.data;
      const formRecord = {
        id: record.id,
        departmentId: record.departmentId || record.department_id,
        costItemId: record.costItemId || record.cost_item_id,
        applicantId: record.applicantId || record.applicant_id,
        amount: record.amount,
        occurrenceDate: record.occurrenceDate || record.occurrence_date,
        recordDate: record.recordDate || record.record_date,
        // 确保costType和paymentStatus是字符串类型，以匹配select选项
        costType: String(record.costType || record.cost_type),
        paymentStatus: String(record.paymentStatus || record.payment_status),
        approvalStatus: record.approvalStatus || record.approval_status,
        description: record.description,
        recordNo: record.recordNo || record.record_no
      };

      // 复制数据到表单
      Object.assign(formData, formRecord);
      dialogVisible.value = true;
    } catch (error) {
      console.error('获取成本记录详情失败:', error);
      ElMessage.error('获取详情失败，请稍后重试');
    }
  };

  // 提交表单
  const handleSubmit = async () => {
    if (formRef.value) {
      formRef.value.validate(async (valid) => {
        if (valid) {
          try {
            // 添加申请人ID（实际应用中应从用户会话获取）
            const submitData = {
              ...formData,
              applicantId: formData.applicantId || 1, // 默认申请人ID
              approvalStatus: 1, // 默认待审批状态
              // 记录编号由后端生成，不需要前端生成
            };

            // 调用真实API
            let response;
            if (formData.id) {
              // 更新操作
              response = await costRecordApi.updateCostRecord(formData.id, submitData);
            } else {
              // 新增操作
              response = await costRecordApi.addCostRecord(submitData);
            }

            // 显示成功消息
            ElMessage.success(formData.id ? '成本记录更新成功' : '成本记录新增成功');

            // 关闭对话框
            dialogVisible.value = false;

            // 重置表单
            if (formRef.value) {
              formRef.value.resetFields();
            }
            resetFormData();

            // 重新加载数据
            getCostRecords();

          } catch (error) {
            console.error('提交成本记录失败:', error);
            ElMessage.error('提交失败，请稍后重试');
          }
        }
      });
    }
  };

  // 重置表单数据
  const resetFormData = () => {
    Object.keys(formData).forEach(key => {
      if (key === 'costType' || key === 'paymentStatus') {
        formData[key] = '1';
      } else {
        formData[key] = '';
      }
    });
  };
  
  // 重置审批表单数据
  const resetApproveFormData = () => {
    Object.keys(approveForm).forEach(key => {
      approveForm[key] = '';
    });
  };
  
  // 打开审批对话框
  const handleApprove = (row) => {
    // 填充表单数据
    approveForm.id = row.id;
    approveForm.recordNo = row.recordNo;
    approveForm.departmentName = row.departmentName;
    approveForm.applicantName = row.applicantName;
    approveForm.amount = row.amount;
    approveForm.description = row.description;
    approveForm.approvalStatus = '';
    approveForm.approvalComment = '';
    
    // 显示对话框
    approveDialogVisible.value = true;
  };
  
  // 提交审批
  const handleApproveSubmit = async () => {
    if (approveFormRef.value) {
      approveFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            // 构建审批数据
            const approvalData = {
              approvalStatus: parseInt(approveForm.approvalStatus),
              approvalComment: approveForm.approvalComment
              // 审批人ID由后端根据JWT自动获取，无需前端传递
            };
            
            // 调用审批API
            await costRecordApi.approveCostRecord(approveForm.id, approvalData);
            
            // 显示成功消息
            ElMessage.success('审批成功');
            
            // 关闭对话框
            approveDialogVisible.value = false;
            
            // 重置表单
            if (approveFormRef.value) {
              approveFormRef.value.resetFields();
            }
            resetApproveFormData();
            
            // 重新加载数据
            getCostRecords();
            
          } catch (error) {
            console.error('审批失败:', error);
            ElMessage.error('审批失败，请稍后重试');
          }
        }
      });
    }
  };

  // 关闭对话框时清理
  const handleDialogClose = () => {
    dialogVisible.value = false;
    // 重置表单
    setTimeout(() => {
      if (formRef.value) {
        formRef.value.resetFields();
        resetFormData();
      }
    }, 300);
  };

  // 分页处理
  const handleSizeChange = (size) => {
    pagination.pageSize = size;
    pagination.currentPage = 1; // 重置为第一页
    getCostRecords();
  };

  const handleCurrentChange = (current) => {
    pagination.currentPage = current;
    getCostRecords();
  };

  // 跳转到指定页
  const jumpToPage = (pageNum) => {
    if (pageNum >= 1 && pageNum <= Math.ceil(pagination.total / pagination.pageSize)) {
      pagination.currentPage = pageNum;
      getCostRecords();
    } else {
      ElMessage.warning('页码超出范围');
    }
  };

  return {
    loading,
    dialogVisible,
    dialogTitle,
    formRef,
    searchForm,
    pagination,
    formData,
    formRules,
    departmentOptions,
    costItemOptions,
    userOptions,
    costRecordsList,
    // 审批相关状态和方法
    approveDialogVisible,
    approveFormRef,
    approveForm,
    approveFormRules,
    // 方法
    getCostRecords,
    getDepartments,
    getCostItems,
    getUsers,
    initializeData,
    formatCurrency,
    getCostTypeTag,
    getPaymentStatusTag,
    getApprovalStatusTag,
    handleSearch,
    handleReset,
    quickFilter,
    handleAdd,
    handleView,
    handleEdit,
    handleSubmit,
    handleDialogClose,
    handleSizeChange,
    handleCurrentChange,
    jumpToPage,
    // 审批相关方法
    handleApprove,
    handleApproveSubmit,
    resetApproveFormData
  };
};

export default useCostRecord;